<template>
  <div class="backup-phone-component">
    <div class="backup-phone-content">
      <!-- 备用号列表 -->
      <div class="backup-phone-list">
        <div v-for="(phone, index) in telInput.length ? telInput : [{}]" :key="index" class="backup-phone-item">
          <div class="phone-input-group">
            <div class="phone-label">备用号 {{ index + 1 }}</div>
            <el-input
              v-model="phone.tel"
              disabled
              placeholder="未设置"
              class="phone-input"
              prefix-icon="el-icon-mobile-phone"
            />
            <el-button
              v-if="phone.tel"
              type="text"
              class="delete-btn"
              @click="deleteBackupPhoneFn(phone.id)"
            >
              <i class="el-icon-delete" />
              删除
            </el-button>
          </div>
        </div>
      </div>

      <!-- 添加按钮区域 -->
      <div class="add-phone-section">
        <el-button
          v-if="backupPhoneCount < 3"
          type="primary"
          plain
          class="add-phone-btn"
          @click="byggshjBtn"
        >
          <i class="el-icon-plus" />
          添加备用手机号
        </el-button>
        <div v-else class="phone-limit-tip">
          <i class="el-icon-info" />
          最多可添加3个备用号
        </div>
      </div>
    </div>

    <!-- 备用手机号弹窗 -->
    <el-dialog
      :title="isEditMode ? '编辑备用手机号' : '添加备用手机号'"
      append-to-body
      :visible.sync="dialogTableVisibleby"
      width="480px"
      :close-on-click-modal="false"
      class="backup-phone-dialog"
    >
      <el-form ref="loginsjhbyForm" :model="loginsjhbyForm" :rules="rulesggsjhby" label-width="100px">
        <el-form-item label="手机号码" prop="mobileTel">
          <el-input
            v-model="loginsjhbyForm.mobileTel"
            placeholder="请输入11位手机号码"
            style="width: 340px;"
            prefix-icon="el-icon-mobile-phone"
            maxlength="11"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="验证码">
          <div class="verification-code-group">
            <el-input
              v-model="loginsjhbyForm.code"
              placeholder="请输入6位验证码"
              class="code-input"
              maxlength="6"
            />
            <el-button
              type="primary"
              :disabled="countdownby > 0"
              class="send-code-btn"
              @click="dxBtnby()"
            >
              {{ countdownby > 0 ? `${countdownby}s后重发` : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogTableVisibleby = false">
          <i class="el-icon-close" />
          取消
        </el-button>
        <el-button type="primary" @click="ggsjhby('loginsjhbyForm')">
          <i class="el-icon-check" />
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUpdatephoneby, getDxyzmby, deleteBackupPhone, getBackupPhones } from '@/api/xwZx'
import { getInfo } from '@/api/login'

export default {
  name: 'GerenZhoxian',
  data() {
    return {
      form: {
        userId: '',
        userName: ''
      },
      telInput: [], // 备用号列表
      countdownby: 0, // 倒计时初始值为0，表示未开始倒计时
      dialogTableVisibleby: false,
      isEditMode: false, // 标识是添加还是编辑模式
      editIndex: -1, // 编辑时的备用号索引
      loginsjhbyForm: {
        mobileTel: '',
        code: '',
        userId: '',
        userName: '',
        uuid: '',
        textMessageType: 0
      },
      rulesggsjhby: {
        mobileTel: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    // 备用号数量
    backupPhoneCount() {
      return this.telInput.filter(phone => phone && phone.tel).length
    }
  },
  mounted() {
    this.getUserInfo()
  },
  methods: {
    // 获取用户信息
    async getUserInfo() {
      try {
        // 优先从Vuex store获取用户信息
        if (this.$store.state.user.user && this.$store.state.user.user.userId) {
          const storeUser = this.$store.state.user.user
          console.log('从Vuex获取用户信息:', storeUser)
          this.form.userId = storeUser.userId || storeUser.id
          this.form.userName = storeUser.username
          this.loginsjhbyForm.userId = storeUser.userId || storeUser.id
          this.loginsjhbyForm.userName = storeUser.username

          this.fetchBackupPhones()
          return
        }

        // 如果store中没有数据，尝试调用API
        console.log('从API获取用户信息')
        let res = await getInfo()
        console.log('API返回用户信息:', res)
        res = res.user
        if (res && (res.userId || res.id)) {
          this.form.userId = res.userId || res.id
          this.form.userName = res.username || res.nickName
          this.loginsjhbyForm.userId = res.userId || res.id
          this.loginsjhbyForm.userName = res.username || res.nickName

          // 获取用户信息后查询备用号
          this.fetchBackupPhones()
        } else {
          throw new Error('用户信息格式不正确')
        }
      } catch (err) {
        console.error('获取用户信息失败:', err)
        console.error('用户信息错误详情:', {
          message: err.message,
          status: err.response && err.response.status ? err.response.status : null,
          data: err.response && err.response.data ? err.response.data : null,
          config: err.config
        })

        // 容错处理：如果API失败，使用默认数据避免页面崩溃
        this.form.userId = 'temp-user-id'
        this.form.userName = 'temp-user'
        this.loginsjhbyForm.userId = 'temp-user-id'
        this.loginsjhbyForm.userName = 'temp-user'

        this.$message.warning('暂时无法获取用户信息，备用手机号功能可能不可用')
      }
    },

    // 查询备用号接口
    async fetchBackupPhones() {
      try {
        console.log('调用查询备用号接口,用户ID:', this.form.userId)
        console.log('请求参数:', { userId: this.form.userId })

        const res = await getBackupPhones({ userId: this.form.userId })
        console.log('备用号接口返回结果:', res)
        this.telInput = res || []
      } catch (err) {
        console.error('查询备用号失败:', err)
        console.error('错误详情:', {
          message: err.message,
          status: err.response && err.response.status ? err.response.status : null,
          data: err.response && err.response.data ? err.response.data : null,
          config: err.config
        })

        if (err.response && err.response.status === 400) {
          this.$message.error('查询备用号失败: 请求参数错误')
        } else if (err.response && err.response.status === 401) {
          this.$message.error('查询备用号失败: 请重新登录')
        } else {
          this.$message.error('查询备用号失败')
        }
      }
    },

    // 打开添加备用号弹窗
    byggshjBtn() {
      this.isEditMode = false
      this.editIndex = -1
      this.dialogTableVisibleby = true
      this.loginsjhbyForm.mobileTel = '' // 清空输入
      this.loginsjhbyForm.code = ''
      this.loginsjhbyForm.userId = this.form.userId
      this.loginsjhbyForm.userName = this.form.userName
    },

    // 删除备用号
    async deleteBackupPhoneFn(id) {
      try {
        await this.$confirm('确认删除该备用手机号吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        await deleteBackupPhone({ telId: id })
        console.log('删除成功')
        this.fetchBackupPhones()
        this.$message.success('删除成功')
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      }
    },

    // 提交备用号（添加）
    ggsjhby(formName) {
      this.$refs[formName].validate(async(valid) => {
        if (valid) {
          try {
            const obj = {
              mobileTel: this.loginsjhbyForm.mobileTel,
              code: this.loginsjhbyForm.code,
              userId: this.loginsjhbyForm.userId,
              textMessageType: this.loginsjhbyForm.textMessageType,
              userName: this.loginsjhbyForm.userName,
              uuid: this.loginsjhbyForm.uuid
            }

            await getUpdatephoneby(obj)
            this.$message.success('添加成功')
            this.dialogTableVisibleby = false
            this.fetchBackupPhones()
            this.$refs.loginsjhbyForm.resetFields()
          } catch (err) {
            console.error('添加失败:', err)
            this.$message.error(err.response && err.response.data && err.response.data.message ? err.response.data.message : '添加失败')
          }
        }
      })
    },

    // 发送验证码
    async dxBtnby() {
      // 校验手机号
      if (!this.loginsjhbyForm.mobileTel) {
        this.$message.error('请输入备用手机号')
        return
      }
      if (!/^1[3-9]\d{9}$/.test(this.loginsjhbyForm.mobileTel)) {
        this.$message.error('手机号格式不正确')
        return
      }

      this.startCountdownby()

      try {
        const params = {
          ...this.loginsjhbyForm,
          textMessageType: 0 // 备用号验证码类型
        }
        console.log('发送验证码请求参数:', params)

        const res = await getDxyzmby(params)
        console.log('验证码接口返回结果:', res)
        this.loginsjhbyForm.uuid = res.uuid
        this.$message.success('验证码已发送')
      } catch (error) {
        console.error('发送验证码失败:', error)
        console.error('验证码错误详情:', {
          message: error.message,
          status: error.response && error.response.status ? error.response.status : null,
          data: error.response && error.response.data ? error.response.data : null,
          config: error.config
        })

        if (error.response && error.response.status === 400) {
          this.$message.error('验证码发送失败: 请求参数错误')
        } else if (error.response && error.response.status === 401) {
          this.$message.error('验证码发送失败: 请重新登录')
        } else {
          this.$message.error('验证码发送失败')
        }
        this.countdownby = 0 // 失败时重置倒计时
      }
    },

    // 开始倒计时
    startCountdownby() {
      this.countdownby = 60 // 设置倒计时时间为60秒
      const interval = setInterval(() => {
        if (this.countdownby > 0) {
          this.countdownby--
        } else {
          clearInterval(interval) // 倒计时结束，清除定时器
        }
      }, 1000)
    }
  }
}
</script>

<style lang="scss" scoped>
.backup-phone-component {
  width: 100%;
}

.backup-phone-content {
  background: #fafafa;
  border: 1px solid #e8eaec;
  border-radius: 6px;
  padding: 20px;
}

.backup-phone-list {
  margin-bottom: 20px;
}

.backup-phone-item {
  margin-bottom: 16px;

  &:last-child {
    margin-bottom: 0;
  }
}

.phone-input-group {
  display: flex;
  align-items: center;
  gap: 12px;
}

.phone-label {
  min-width: 80px;
  font-size: 13px;
  color: #666;
  font-weight: 500;
}

.phone-input {
  flex: 1;
  max-width: 280px;
}

.delete-btn {
  color: #f56c6c;
  padding: 0;

  &:hover {
    color: #f02d2d;
    background: none;
  }

  i {
    margin-right: 4px;
  }
}

.add-phone-section {
  display: flex;
  align-items: center;
  justify-content: center;
  padding-top: 16px;
  border-top: 1px dashed #d9d9d9;
}

.add-phone-btn {
  padding: 8px 20px;

  i {
    margin-right: 6px;
  }
}

.phone-limit-tip {
  color: #909399;
  font-size: 13px;
  display: flex;
  align-items: center;
  gap: 6px;

  i {
    font-size: 14px;
  }
}

// 弹窗样式
.backup-phone-dialog {
  .el-dialog__header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 6px 6px 0 0;

    .el-dialog__title {
      color: white;
      font-weight: 500;
    }

    .el-dialog__headerbtn .el-dialog__close {
      color: white;

      &:hover {
        color: #f0f0f0;
      }
    }
  }

  .el-dialog__body {
    padding: 30px 20px 20px;
  }
}

.verification-code-group {
  display: flex;
  align-items: center;
  gap: 12px;
}

.code-input {
  flex: 1;
}

.send-code-btn {
  min-width: 110px;
  padding: 8px 16px;
}

.dialog-footer {
  padding: 0 20px 20px;
  text-align: right;

  .el-button {
    margin-left: 12px;
    padding: 8px 20px;

    i {
      margin-right: 4px;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .backup-phone-content {
    padding: 16px;
  }

  .phone-input-group {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .phone-label {
    min-width: auto;
  }

  .phone-input {
    width: 100%;
    max-width: none;
  }

  .verification-code-group {
    flex-direction: column;
    gap: 12px;
  }

  .send-code-btn {
    width: 100%;
  }
}
</style>
